import React, { useState, useEffect, useMemo } from 'react';
import { Form, message } from 'antd';
import { ApplyUpdateService } from '../services/UpdateService';
import { DBZ_STATE, SHZ_SQSTATE, SQ_flowBusinessType, getNowData } from './Format';
import { getPosIDs, getUserDepID, getUserID } from '@/utils';
import { IContractsActionEnum } from './ApplyReducer';
import moment from 'moment';

const { success, warning } = message;
/**
 * @useNeedUpdate 详情页hooks逻辑
 * @returns isShowState 渲染状态
 * @returns change 修改渲染状态
 * @returns submit 提交事件
 */
export function useApplyUpdate({ currentStep, info, source, state, isRefresh }: Record<string, any>) {
  // const { ProjectInfo } = useContext(ApplyUpdateContext);
  // 解构state
  const { supplyTK, page, setSuccessMaterials, ProjectInfo, dispatch } = state;
  // 取消申请表单实例
  const [cancelForm] = Form.useForm();
  // 办理审批表单实例
  const [auditRecordForm] = Form.useForm();

  // 步骤条第一步基本信息实例
  const stepsBaseInfoRef = React.useRef<any>(null);
  // 步骤条第二步标包信息实例
  const stepsPackRef = React.useRef<any>(null);
  // 步骤条第三步申请信息实例
  const stepsApplykRef = React.useRef<any>(null);

  // 存储当前申请信息
  const [applyInfo, setApplyInfo] = useState<Record<string, any>>({});

  // 办理审批弹窗渲染状态
  const [isShowAuditModal, setIsShowAuditModal] = useState<boolean>(false);
  const onChangeAuditModalState = (state: boolean, type: string = 'agree') => {
    setIsShowAuditModal(state);
    if (state && type == 'agree') {
      auditRecordForm.setFieldsValue({ auditType: 1, auditReason: '通过' });
    }
    if (state && type == 'disagree') {
      auditRecordForm.setFieldsValue({ auditType: 2, auditReason: '退回' });
    }
  };

  // API 接口
  const { findApplyService, findPlanService, addApplyService, addPackService, getPackService, editApplyService, editPackServices } = ApplyUpdateService();

  /** 详情接口 */
  const { findApplyRun, findApplyLoading } = findApplyService();
  /** 新增接口 */
  const { addApplyRun, addApplyLoading } = addApplyService();
  /** 编辑接口 */
  const { editApplyRun, editApplyLoading } = editApplyService();
  /** 计划详情 */
  const { findPlanRun, findPlanLoading } = findPlanService();
  /** 添加标包接口 */
  const { addPackRun, addPackLoading } = addPackService();
  /** 获取标包接口 */
  const { getPackRun, getPackLoading } = getPackService();
  /** 编辑标包 */
  const { editPackRun, editPackLoading } = editPackServices();

  /** 全局loading */
  const loading = useMemo(() => {
    return findApplyLoading || addApplyLoading || findPlanLoading || addPackLoading || getPackLoading || editApplyLoading || editPackLoading;
    // mapLoading
  }, [
    findApplyLoading,
    addApplyLoading,
    findPlanLoading,
    addPackLoading,
    getPackLoading,
    editApplyLoading,
    editPackLoading,
    // mapLoading
  ]);

  /** 申请详情 */
  const fetchFindApply = async (params: Record<string, any>) => {
    const { msgFlag, msg, obj } = await findApplyRun(params);
    if (msgFlag) {
      /** 保存详情 */
      setApplyInfo(obj);

      /** 在上下文中保存一份 [编辑的时候还有取出来用] */
      dispatch({
        type: IContractsActionEnum.UpdataProJect,
        payload: {
          projectCode: obj?.projectCode,
          projectFlag: obj?.projectFlag,
          projectID: obj?.projectID,
          projectName: obj?.projectName,
          projectSum: obj?.projectSum,
        },
      });

      /** 申请详情中是否有标包信息 && 获取标包接口调用 */
      if (obj?.mpurchasePacks && obj?.mpurchasePacks?.length) {
        let packIds = obj?.mpurchasePacks?.map((item) => item?.id).join(',');
        fetchGetPack({ packIds }, obj);
      }
    } else {
      warning(msg);
    }
  };

  /** 添加采购申请 */
  const fetchAddApply = async (params: Record<string, any>) => {
    const { msgFlag, msg, obj } = await addApplyRun(params);
    if (msgFlag) {
      success(msg);
      if (obj) fetchFindApply({ id: obj });
    } else {
      warning(msg);
    }
  };

  /** 编辑采购申请 */
  const fetchEditApply = async (params: Record<string, any>) => {
    const { msgFlag, msg, obj } = await editApplyRun(params);
    if (msgFlag) {
      success(msg);
      fetchFindApply({ id: obj });
    } else {
      warning(msg);
    }
  };

  /** 获取标包数据 */
  const fetchGetPack = async (params: Record<string, any>, resObj: any) => {
    let { msgFlag, msg, obj } = await getPackRun(params);

    /** 标包数据排序 - 创建时间最早的在第一个 */
    obj?.sort((a, b) => {
      var dateA: any = new Date(a?.createTime);
      var dateB: any = new Date(b?.createTime);
      return dateA - dateB;
    });

    /** obj = 包的集合 */
    obj?.forEach((item) => {
      /** mpurchaseSourceMaterials = 包下面的标的集合 */
      item?.mpurchaseSourceMaterials?.forEach((ite) => {
        /** mmaterial = 物料的详细数据 */

        if (ite?.materialType) {
          ite.fullName = ite?.mmaterial?.fullName; // 标的名称
          ite.specInfo = ite?.mmaterial?.specInfo; // 规格型号（参数）
          ite.needParams = ite?.mmaterial?.specInfo; // 规格要求（替换）
          ite.supplyKindName = ite?.mmaterial?.materialTypeName; // 标的名称
          ite.supplyKind = ite?.mmaterial?.materialType; // 标的名称 【修改= materialTypeName -> materialType】
        } else {
          ite.needParams = ite?.specInfo; // 规格要求（替换）
        }

        /** 标的类型取值 */
        // ite.supplyTypeName = ite?.mmaterial?.supplyTypeName; // 标的类型 [翻译]
        // ite.supplyType = ite?.mmaterial?.supplyType; // 标的类型

        /** 操作会修改expectNum, 要另外保存一份【1，接口请求回来的标包，2，锁定数量要扣除】 */
        ite.expectNum_s = ite?.expectNum;

        /** 实施物料id重新给一个字段，用于编辑 */
        ite.CarryID = ite?.id;
      });

      item.mpurchaseNeedMaterials = item?.mpurchaseSourceMaterials;
      item.SourceData = item?.mpurchaseSourceMaterials || []; // 一份源数据
      delete item?.mpurchaseSourceMaterials;
    });

    // 更新
    setSuccessMaterials(obj?.[page]?.mpurchaseNeedMaterials);

    if (msgFlag) {
      success(msg);
      const param = { ...resObj, packs: obj };
      setApplyInfo(param);
    } else {
      warning(msg);
    }
  };

  /** 编辑标包数据 */
  const fetchEditPack = async (params) => {
    let result = await editPackRun(params);
    if (result?.msgFlag) {
      message?.success(result?.msg);
      if (result?.obj) fetchFindApply({ id: result?.obj });
    }
  };

  /** 添加标包数据 */
  const fetchAddPack = async (params: Record<string, any>) => {
    const { msgFlag, msg, obj } = await addPackRun(params);
    if (msgFlag) {
      success(msg);
      fetchFindApply({ id: applyInfo?.id });
    } else {
      warning(msg);
    }
  };

  /**
   * @submit 提交事件
   */
  const submit = {
    submitApply: () => {
      if (applyInfo?.mpurchasePacks) {
        setWorkFlowInfoObj({
          selectFlowRows: applyInfo,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        message?.warn('请先暂存标包后再发起流程审核！');
      }
    },
    submitAudit: async () => {
      const result = await auditRecordForm.validateFields();
    },
    saveApply: async () => {
      /** update页面底部暂存按钮事件 【详情对象：applyInfo】*/
      if (currentStep == 0) {
        /** 步骤条第一步事件 && 判断详情对象是否有值 */
        if (applyInfo && applyInfo?.id) {
          const { validateFields } = stepsBaseInfoRef.current;
          const result = await validateFields();
          const param = {
            ...applyInfo,
            ...result,
            // projectSum: ProjectInfo?.projectSum,
            // projectName: ProjectInfo?.projectName,
            // projectCode: ProjectInfo?.projectCode,
            // projectID: ProjectInfo?.projectID,
            purchProjectName: result?.applyTitle,
            purchProjectCode: result?.applyCode,
            busiFlag: result?.busiDepartmentID ? 1 : 0,
            unitFlag: result?.unitDepartmentID ? 1 : 0,
            applyTime: moment(result?.applyTime).format('YYYY-MM-DD 00:00:00'),
          };
          fetchEditApply(param); /** 编辑接口 */
        } else {
          const { validateFields } = stepsBaseInfoRef.current;
          const result = await validateFields();
          const param = {
            // projectSum: ProjectInfo?.projectSum,
            // projectName: ProjectInfo?.projectName,
            // projectCode: ProjectInfo?.projectCode,
            // projectID: ProjectInfo?.projectID,
            ...result,
            purchProjectName: result?.applyTitle,
            purchProjectCode: result?.applyCode,
            busiFlag: result?.busiDepartmentID ? 1 : 0,
            unitFlag: result?.unitDepartmentID ? 1 : 0,
            applyTime: moment(result?.applyTime).format('YYYY-MM-DD 00:00:00'),
          };
          fetchAddApply(param); /** 新增接口 */
        }
      } else if (currentStep == 1) {
        /** 步骤条第二步事件 */
        const { validateFields } = stepsPackRef.current;
        const result = await validateFields();
        if (result === false) {
          warning('请添加标包信息');
          return;
        }

        /** 当前包数据 */
        let Pack = result[page - 1];
        /** 获取每一个子项 */
        let newarr: any[] = [];
        Pack?.mpurchaseNeedMaterials?.forEach((item: any, _, arrs) => {
          // 零星采购
          if (applyInfo?.supplyWay == 1) {
            let obj: Record<string, any> = {
              needMID: item?.needMID,
              expectNum: item?.expectNum,
              expectPrice: item?.expectPrice,
              expectSum: item?.expectSum,
              mergeFlag: arrs?.length > 1 ? 1 : 0,
              specInfo: item?.needParams, //规格要求（参数）
              unitBusiness: item?.unitBusiness, //量化单位
              fullName: item?.fullName, //物料名称
              supplyType: item?.supplyType, //采购类别
              projectCode: item?.projectCode,
              projectName: item?.projectName,
              projectSum: item?.projectSum,
            };
            /** 这是在详情接口返回时带的实施id */
            if (item?.CarryID) obj.id = item?.CarryID;
            newarr?.push(obj);
          } else {
            // 月度采购
            let { customNeedMatrials } = item;
            customNeedMatrials?.forEach((ite, _, arr) => {
              let obj: Record<string, any> = {
                needMID: ite?.needMID,
                expectNum: ite?.expectNum,
                expectPrice: ite?.expectPrice,
                expectSum: ite?.expectSum,
                mergeFlag: arr?.length > 1 ? 1 : 0,
                specInfo: ite?.needParams, //规格要求（参数）
                unitBusiness: ite?.unitBusiness, //量化单位
                fullName: ite?.fullName, //物料名称
                supplyType: ite?.supplyType, //采购类别
                projectCode: item?.projectCode,
                projectName: item?.projectName,
                projectSum: item?.projectSum,
              };
              /** 这是在详情接口返回时带的实施id */
              if (ite?.CarryID) obj.id = ite?.CarryID;
              newarr?.push(obj);
            });
          }
        });

        /** 计算总价 */
        let sum = 0;
        newarr?.forEach((item) => {
          let itemExpectSum = Number(item?.expectNum) * Number(item?.expectPrice);
          sum += itemExpectSum;
          item.expectSum = itemExpectSum;
        });

        /** 整合数据 */
        let resObj = {
          // ...supplyTK,
          supplyType: supplyTK?.supplyType,
          ...Pack,
          applyID: applyInfo?.id,
          expectSum: sum,
          state: DBZ_STATE(),
          supplyWay: applyInfo?.supplyWay,
          mpurchaseSourceMaterials: getNowData(newarr),
          changeFlag: 0,
          intentFlag: 0,
        };

        delete resObj?.mpurchaseNeedMaterials;
        if (!resObj?.mpurchaseSourceMaterials || JSON.stringify(resObj?.mpurchaseSourceMaterials) == '[]') {
          message?.warn('请选择标的后，再暂存！');
          return;
        }

        if (resObj?.mpurchaseSourceMaterials?.length) {
          const projectFlag = resObj?.mpurchaseSourceMaterials?.find((item) => {
            if (!item?.projectCode) {
              return item;
            }
          });
          if (projectFlag) {
            message?.warn('请选择物料的项目来源！');
            return;
          }
        }

        if (
          resObj?.supplyWay == 1 &&
          Number(resObj?.expectSum) >= 1000000 &&
          (Number(resObj?.directorMeetingFlag) == 0 || resObj?.directorMeetingFlag == undefined)
        ) {
          message?.warn('请确认是否通过主任办公会审议！');
          return;
        }

        // return

        if (resObj?.id) {
          let delSourceMaterials: any[] = [];
          // 详情返回的原本数据 找到需要删除的
          let { SourceData, mpurchaseSourceMaterials } = resObj;
          const ids = SourceData?.map((item) => item?.CarryID);
          const newids = mpurchaseSourceMaterials.map((item) => item?.id)?.filter(Boolean);
          ids?.forEach((item) => {
            if (!newids?.includes(item)) {
              delSourceMaterials?.push(item);
            }
          });
          resObj.delSourceMaterials = delSourceMaterials?.join(',');
          // 编辑标包接口
          fetchEditPack(resObj);
        } else {
          // 新增标包接口
          fetchAddPack(resObj);
        }
      }
    },
  };

  /** 数据回显 */
  useEffect(() => {
    if (Object.keys(info).length) {
      if (source == 'apply') {
        // 申请管理进入
        fetchFindApply({ id: info.id });
      }
      // else if (source == 'plan') {
      //   // 计划管理进入
      //   fetchFindPlan({ id: info.id });
      // }
    }
  }, [info, source]);

  // 点击按钮保存数据和弹框控制 =============================工作流使用==============================START

  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });
  const onChangeWorkFlowInfoObj = (params: Record<string, any>) => setWorkFlowInfoObj(params);
  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /** 处理工作流功能 权限 */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (applyInfo?.state == SHZ_SQSTATE()) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = SQ_flowBusinessType();
    const taskHandInfo: Record<string, any> = applyInfo?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [applyInfo]);

  // 是否可以办理流程
  const nodesFlowListMemo = useMemo(() => {
    /** 演示注释:【振豪本地无工作流数据，所以要直接返回true】 */
    const taskHandInfo: Record<string, any> = applyInfo?.paramObject?.[SQ_flowBusinessType()];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      return taskHandInfo?.mactivitiTaskList?.[0];
    } else {
      return false;
    }

    // return true // [演示]
  }, [applyInfo?.paramObject]);

  // 点击按钮保存数据和弹框控制 =============================工作流使用==============================END

  /** 获取详情方法 */
  const reloadInfoService = () => {
    fetchFindApply({ id: applyInfo?.id });
  };

  useEffect(() => {
    if (isRefresh) {
      reloadInfoService();
    }
  }, [isRefresh]);

  return {
    applyInfo,
    loading,
    ref: {
      stepsBaseInfoRef,
      stepsPackRef,
      stepsApplykRef,
    },
    form: {
      cancelForm,
      auditRecordForm,
    },
    isShowState: {
      isShowAuditModal,
      workflowPowerAllBtn,
      workFlowInfoObj,
      showSwitchFlow,
      nodesFlowListMemo,
    },
    change: {
      onChangeAuditModalState,
      onChangeWorkFlowInfoObj,
      setShowSwitchFlow,
      closeSwitchFlowModal,
      reloadInfoService,
    },
    submit,
  };
}
